package com.three.crm.util;

import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SignUtil {

    public static String genSign(JSONObject jsonObject) throws JSONException {
        List<String> keyString = new ArrayList<>();
        List<JsonObject> keyList = new ArrayList<>();
        Iterator iterator = jsonObject.keys();
        try {
            while (iterator.hasNext()){
                String key = (String) iterator.next();
                String value = jsonObject.getString(key);
                keyString.add(key);
                JSONObject tempObj = new JSONObject();
                tempObj.put(key,value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Collections.sort(keyString);
        String res = "";
        for (int i = 0; i < keyString.size(); i++) {
            String key = keyString.get(i);
            res += key;
            String value = jsonObject.getString(key);
            res += value;
        }
        res += "guatu@330987#";
        return md5(res);
    }

    public static String md5(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException",e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10){
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}
